package com.wjggy.core.common.util;

import java.awt.image.BufferedImage;
import java.util.Enumeration;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import com.wjggy.core.common.util.cookie.CookieUtils;
import com.wjggy.core.exception.ImageException;

/**
 *  <p>Description:  图片验证码</p>
 *  <p>Copyright:Copyright (c) 2012  </p>
 *  <p>Company:wjggy  </p>
 *  @author xiaofan.yu  
 *  @date   2012-1-8 下午10:22:02    
 *  @project  wjggy
 *  @version  1.0.0
 *  @see   
 *  @since 1.6
 */
public class ImageUtils extends HttpServlet implements Servlet {
	private static Logger log = Logger.getLogger(ImageUtils.class);
	private Properties props = new Properties();
	private Producer kaptchaProducer = null;

	public void init() throws ServletException {
	}
	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
		ImageIO.setUseCache(false);
		Enumeration<?> initParams = conf.getInitParameterNames();
		while (initParams.hasMoreElements()) {
			String key = (String) initParams.nextElement();
			String value = conf.getInitParameter(key);
			this.props.put(key, value);
		}
		Config config = new Config(this.props);
		this.kaptchaProducer = config.getProducerImpl();
	}
	
	/**
	 * 生成验证码
	 */
	public void doGet(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse)   {
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
		httpServletResponse.setHeader("Pragma", "no-cache");
		String capText = this.kaptchaProducer.createText();
		try {
			CookieUtils.addAuthCode(httpServletResponse, capText);
			BufferedImage bi = this.kaptchaProducer.createImage(capText);
			ServletOutputStream out = httpServletResponse.getOutputStream();
			ImageIO.write(bi, "jpg", out);
			out.close();
		} catch (Exception e) {
			log.error(e);
			throw new ImageException(e);
		} 
	}
}